<template>
  <div class="profile">
    <!--    <div class="account-settings-info-title">-->
    <!--      <span data-v-26b608e6="">消息通知</span>-->
    <!--    </div>-->
    <div class="account-settings-info-view">
      <avue-crud
        ref="crud"
        v-model="form"
        :option="option"
        :table-loading="loading"
        :data="data"
        :page="page"
        :before-open="beforeOpen"
        :cell-style="cellStyle"
        :row-style="rowStyle"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @row-click="rowClick"
        @refresh-change="refresh"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @on-load="onLoad"
      >
        <template slot="menuLeft">
          <el-button
            :plain="notificationType[0]==0"
            type="primary"
            size="small"
            @click="handleFilterRecord(0)"
          >
            全部类型消息
          </el-button>
          <el-button
            :plain="notificationType[1]===0"
            type="primary"
            size="small"
            @click="handleFilterRecord(1)"
          >
            站内信
          </el-button>
          <el-button
            :plain="notificationType[2]===0"
            type="primary"
            size="small"
            @click="handleFilterRecord(2)"
          >
            邮件
          </el-button>
          <el-button
            :plain="notificationType[3]===0"
            type="primary"
            size="small"
            @click="handleFilterRecord(3)"
          >
            短信
          </el-button>
          <el-button
            :plain="notificationType[4]===0"
            type="primary"
            size="small"
            @click="handleFilterRecord(4)"
          >
            微信公众号
          </el-button>
          <el-button
            :plain="notificationType[5]===0"
            type="primary"
            size="small"
            @click="handleFilterRecord(5)"
          >
            微信小程序消息
          </el-button>
          <el-button
            :plain="notificationType[6]===0"
            type="primary"
            size="small"
            @click="handleFilterRecord(6)"
          >
            APP消息
          </el-button>
        </template>
        <!--      <template slot="menuRight">-->
        <!--        <el-button type="primary" icon="el-icon-plus" circle size="small" />-->
        <!--      </template>-->
      </avue-crud>
      <div class="page">
        <div class="left">
          <el-checkbox v-model="checkAll" @change="changeCheckAll" />
          <el-button :disabled="btnDisabledStatus" size="small" @click="handleDelete">
            删除
          </el-button>
          <el-button :disabled="btnDisabledStatus" size="small" @click="handleRead">
            标记已读
          </el-button>
          <el-button size="small" @click="handleReadAll">
            全部已读
          </el-button>
          <el-button size="small" @click="handleDeleteAll">
            全部删除
          </el-button>
        </div>
        <div class="right">
          <el-pagination
            :small="$device.isMobile"
            :pager-count="$device.isMobile?5:7"
            :page-size="newPage.pageSize"
            :page-sizes="newPage.pageSizes"
            :total="newPage.total"
            current-page.sync="1"
            background
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="sizeChange"
            @current-change="currentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import { mapGetters } from 'vuex'

const addSysNotificationAction = 'sys/notification/addSysNotification'
const updateSysNotificationAction = 'sys/notification/updateSysNotification'
const removeSysNotificationAction = 'sys/notification/removeSysNotification'
const removeSysNotificationsAction = 'sys/notification/removeSysNotifications'
const getSysNotificationByIdAction = 'sys/notification/getSysNotificationById'
const getSysNotificationPageListAction = 'sys/notification/pageSysNotification'
const readNotificationAction = 'sys/notification/readNotification'
export default {
  name: 'Notification',
  data () {
    return {
      notificationType: [1, 0, 0, 0, 0, 0, 0],
      checkAll: false,
      btnDisabledStatus: true,
      form: {},
      query: {},
      loading: true,
      newPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: null
      },
      selectionList: [],
      option: {
        // title: '系统通知表(邮件,短信,微信公众号消息,微信小程序消息,app消息)',
        border: true,
        menu: false,
        lazy: true,
        tip: true,
        tipPlacement: 'top-start',
        index: true,
        indexLabel: '序号',
        indexFixed: true,
        multiple: false,
        selection: true,
        selectionWidth: 60,
        selectionFixed: false,
        searchShow: false,
        searchMenuSpan: 5,
        addBtn: false,
        excelBtn: false,
        printBtn: false,
        viewBtn: true,
        editBtn: false,
        delBtn: true,
        dialogDrag: true,
        dialogDirection: 'rtl',
        dialogType: 'dialog',
        column: [
          {
            label: '标题',
            prop: 'title',
            type: 'input',
            hide: false,
            span: 24,
            width: 190,
            showWordLimit: true,
            maxlength: 200,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入通知标题',
              trigger: 'blur'
            }]
          },
          {
            label: '内容',
            prop: 'content',
            type: 'textarea',
            hide: false,
            span: 24,
            showWordLimit: true,
            maxlength: 9000,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入通知内容',
              trigger: 'blur'
            }]
          },
          {
            label: '类型',
            prop: 'notificationType',
            type: 'select',
            dicData: [
              { label: '站内信', value: 1 },
              { label: '邮件', value: 2 },
              { label: '短信', value: 3 },
              { label: '微信公众号', value: 4 },
              { label: '微信小程序消息', value: 5 },
              { label: 'APP消息', value: 6 }
            ],
            hide: false,
            span: 24,
            width: 130,
            showWordLimit: true,
            maxlength: 200,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请选择通知类型',
              trigger: 'blur'
            }]
          },
          {
            label: '时间',
            prop: 'updateTime',
            width: 180
          }
        ]
      },
      originalData: [],
      data: []
    }
  },
  computed: {
    ...mapGetters(['permissions', 'website', 'userInfo']),
    ids () {
      const ids = []
      this.selectionList.forEach((e) => {
        ids.push(e.id)
      })
      return ids
    }
  },
  watch: {},
  methods: {
    changeCheckAll (newValue) {
      if (newValue) {
        this.selectionList = this.data
        this.$refs.crud.toggleSelection(this.data)
      } else {
        this.selectionList = []
        this.$refs.crud.toggleSelection()
      }
    },
    handleFilterRecord (type) {
      const filterData = type > 0 ? this.originalData.filter(d => d.notificationType === type) : this.originalData
      this.notificationType = this.notificationType.map((n, index) => {
        n = type === index ? 1 : 0
        return n
      })
      this.data = filterData
    },
    handleRead () {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm(`您确定要标记选中的${this.selectionList.length}条消息为已读吗？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { ids: this.ids }
          return this.$store.dispatch(readNotificationAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const message = res.message
          if (resCode === 0) {
            this.$message({
              type: 'success',
              message: '标记已读消息操作成功!'
            })
            this.onLoad(this.page)
            this.$refs.crud.toggleSelection()
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: message || '标记已读消息失败,请稍后再试!'
            })
          }
        }).catch((action) => {
          this.loading = false
        })
    },
    handleReadAll () {
      this.selectionList = this.data
      this.handleRead()
    },
    rowStyle ({ row, column, rowIndex }) {
      return {}
    },
    cellStyle ({ row, column, rowIndex, columnIndex }) {
      if (row.readStatus === 1) {
        return {
          fontWeight: '400'
        }
      } else {
        return {
          fontWeight: '700'
        }
      }
    },
    rowSave (row, loading, done) {
      loading()
      this.$store.dispatch(addSysNotificationAction, row).then((res) => {
        done()
        const resCode = res.code
        const message = res.message
        if (resCode === 0) {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '保存操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: message || '保存数据失败,请稍后再试!'
          })
        }
      }).catch(() => {
        done()
        this.$message({
          type: 'error',
          showClose: true,
          message: '保存数据失败,请稍后再试!'
        })
      })
    },
    rowUpdate (row, index, loading, done) {
      loading()
      this.$store.dispatch(updateSysNotificationAction, row).then((res) => {
        done()
        const resCode = res.code
        const message = res.message
        if (resCode === 0) {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '编辑操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: message || '编辑数据失败,请稍后再试!'
          })
        }
      }).catch(() => {
        done()
        this.$message({
          type: 'error',
          showClose: true,
          message: '编辑数据异常,请稍后再试!'
        })
      })
    },
    rowDel (row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { id: row.id }
          return this.$store.dispatch(removeSysNotificationAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const message = res.message
          if (resCode === 0) {
            this.onLoad(this.page)
            this.$message({
              type: 'success',
              message: '删除操作成功!'
            })
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: message || '删除数据失败,请稍后再试!'
            })
          }
        }).catch(() => {
          this.loading = false
        })
    },
    handleDeleteAll () {
      this.selectionList = this.data
      this.handleDelete()
    },
    handleDelete () {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          const idParams = { ids: this.ids }
          return this.$store.dispatch(removeSysNotificationsAction, idParams)
        })
        .then((res) => {
          this.loading = false
          const resCode = res.code
          const message = res.message
          if (resCode === 0) {
            this.$message({
              type: 'success',
              message: '批量删除操作成功!'
            })
            this.onLoad(this.page)
            this.$refs.crud.toggleSelection()
          } else {
            this.loading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: message || '批量删除数据失败,请稍后再试!'
            })
          }
        }).catch(() => {
          this.loading = false
        })
    },
    rowClick (row, event, column) {
      this.$refs.crud.rowView(row, column)
      // 标记为已读
      const idParams = { ids: [row.id] }
      this.$store.dispatch(readNotificationAction, idParams).then((res) => {
        const resCode = res.code
        if (resCode === 0) {
          row.readStatus = 1
        }
      })
    },
    refresh ({ page, searchForm }) {
      this.onLoad(page)
    },
    beforeOpen (done, type) {
      if (['edit', 'view'].includes(type)) {
        const idParams = { id: this.form.id }
        this.$store.dispatch(getSysNotificationByIdAction, idParams).then((res) => {
          const resCode = res.code
          const message = res.message
          if (resCode === 0) {
            this.form = res.data
          } else {
            this.$message({
              type: 'error',
              showClose: true,
              message: message || '查询数据失败,请稍后再试!'
            })
          }
        }).catch((err) => {
          console.log(err)
          this.$message({
            type: 'error',
            showClose: true,
            message: '查询数据异常,请稍后再试!'
          })
        })
      }
      done()
    },
    searchReset () {
      this.query = {}
      this.onLoad(this.newPage)
    },
    searchChange (params, done) {
      done()
      this.query = params
      this.newPage.currentPage = 1
      this.onLoad(this.newPage, params)
    },
    selectionChange (list) {
      this.selectionList = list
      this.btnDisabledStatus = this.selectionList.length === 0
      this.checkAll = this.selectionList.length > 0
    },
    selectionClear () {
      this.selectionList = []
      this.$refs.crud && this.$refs.crud.toggleSelection()
    },
    currentChange (currentPage) {
      this.newPage.currentPage = currentPage
    },
    sizeChange (pageSize) {
      this.newPage.pageSize = pageSize
    },
    onLoad (page, params = {}) {
      this.loading = true
      let queryData = {
        pageNo: page.currentPage,
        pageSize: page.pageSize,
        userId: this.userInfo.id
      }
      queryData = Object.assign(queryData, Object.assign(params, this.query))
      this.$store.dispatch(getSysNotificationPageListAction, queryData).then((res) => {
        this.loading = false
        const resCode = res.code
        const message = res.message
        if (resCode === 0) {
          const data = res.data
          this.data = data.records
          this.originalData = data.records
          this.newPage.total = parseInt(data.total)
          this.selectionClear()
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: message || '查询数据失败,请稍后再试!'
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          showClose: true,
          message: '查询数据异常,请稍后再试!'
        })
      })
    }
  },
  head () {
    return {
      title: '消息通知 | 个人中心',
      meta: [
        { hid: 'description', name: 'description', content: '消息通知,个人中心' }
      ]
    }
  }
}
</script>

<style lang="scss" scoped>
  .profile {
    flex: 1 1;
    padding: 8px 40px;

    .account-settings-info-title {
      color: rgba(0,0,0,.85);
      font-size: 20px;
      font-weight: 500;
      line-height: 28px;
      margin-bottom: 12px;
    }
    .account-settings-info-view {
      padding-top: 12px;
    }
  }
  .ant-list-empty-text {
    color: rgba(0,0,0,.45);
    font-size: 14px;
    padding: 16px;
    text-align: center;
  }
  .page {
    .left {
      float: left;
      height: 30px;
      margin-top: 15px;
      margin-bottom: 10px;
      padding-left: 25px;
      /*padding: 10px 20px;*/
    }
    .right {
      float: right;
      height: 25px;
      margin-top: 15px;
      margin-bottom: 10px;
      /*padding: 10px 20px;*/
    }
  }
</style>
